<script>
import UserApi from "@/api/user";
import { useUserStore } from "@/stores/user";
import { mapStores } from "pinia";
import { ElNotification } from "element-plus";
export default {
  data() {
    return {
      uid: null,
      url: "https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png",
    };
  },
  methods: {
    toProfile() {
      window.location.assign("http://localhost:5006/info");
    },
    async logout() {
      console.log(this.userStore.userId);
      let user_id = this.userStore.userId ? this.userStore.userId : 0;
      let api = new UserApi();
      let result = await api.logout(user_id);
      console.log(result);
      if (result.data.code === 200) {
        this.userStore.$reset();
        localStorage.removeItem("user");
        ElNotification({
          title: "Success",
          message: result.data.msg,
          type: "success",
        });
      } else {
        ElNotification({
          title: "Error",
          message: result.data.msg,
          type: "error",
        });
      }
    },
  },
  computed: {
    ...mapStores(useUserStore),
  },
  beforeMount() {
    this.uid = this.userStore.userId;
    this.url = this.userStore.avatarUrl;
    console.log("当前用户ID:", this.uid);
  },
};
</script>

<template>
  <div class="headerInfo">
    <header>
      <div class="logo">
        <img alt="Market logo" class="logo" src="@/assets/logo.svg" width="125" height="125" />
        <h1>校园二手交易平台</h1>
      </div>
      <div class="log-reg">
        <span v-if="this.userStore.userId">
          <el-avatar
            :size="45"
            :src="url"
            style="cursor: pointer"
            @click="toProfile"
          />
        </span>
        <span v-if="!this.userStore.userId" class="tab-login"><router-link to="/login">登录</router-link></span>
        <span v-if="!this.userStore.userId" class="tab-register"><router-link to="/register">注册</router-link></span>
        <span v-if="this.userStore.userId" class="tab-logout"> <button @click="logout">退出</button></span>
      </div>
    </header>
  </div>
</template>

<style scoped>
span {
  line-height: 50px;
}

.headerInfo {
  background-color: #fff;
}

button {
  background-color: #fff;
  border: none;
  cursor: pointer;
  color: #333333;
  padding: 0;
}

.logo {
  flex: auto;
  display: flex;
  justify-content: flex-start; /* 确保内容从左端开始 */
}

.logo img {
  height: 80px;
  flex: 0 0 80px;
}

.logo h1 {
  flex: 1 1 auto;
  margin-left: 16px;
}

.tab-login {
  padding-left: 10px;
}

.tab-login,
.tab-register{
  padding-right: 10px;
}

.tab-logout{
  padding-left: 10px;
}

.log-reg {
  margin-right: 200px;
  display: flex;
  text-align: center;
}

.log-reg a {
  color: #333333;
}
</style>
